import { defineStore } from "pinia";
import { message } from "ant-design-vue";

export const useSocket = defineStore("Socket", () => {
  let webSocket: WebSocket | null = null;
  let activeTimer: ReturnType<typeof setInterval> | null = null;
  let lastActiveTime: number = -1;
  let reconnectTimer: ReturnType<typeof setInterval> | null = null;
  let reconnectCount = 0;
  let reconnectTime = -1;
  let activeClose = false;
  let reconnectIng = false;

  function InitWS(
    url: string,
    connectionKey: any,
    activeToken: any,
    callBack: (data: any) => void
  ): WebSocket | null {
    if (!window.WebSocket) {
      message.error("你的浏览器不支持Socket的长连接!");
      return null;
    }

    webSocket = new WebSocket(url);

    if (webSocket) {
      webSocket.onopen = (event) => {
        webSocket?.send(JSON.stringify(connectionKey));
        lastActiveTime = -1;
        reconnectCount = 0;
        reconnectTime = -1;
        reconnectIng = false;

        if (reconnectTimer) {
          clearInterval(reconnectTimer);
        }

        if ( webSocket && webSocket.readyState === WebSocket.OPEN) {
          activeTimer = setInterval(() => {
            keepAlive(activeToken);
          }, 60000);
        }
      };

      webSocket.onmessage = (event) => {
        callBack(event.data);
      };

      webSocket.onclose = () => {
        reconnect(url, connectionKey, activeToken, callBack);
      };
    }

    return webSocket;
  }

  function keepAlive(activeToken: any) {
    if (
      webSocket &&
      webSocket.readyState === WebSocket.OPEN &&
      webSocket.bufferedAmount === 0
    ) {
      webSocket.send(JSON.stringify(activeToken));
      lastActiveTime = Date.now();
    }
  }

  function send(data: any) {
    if (webSocket && webSocket.readyState === WebSocket.OPEN) {
      webSocket.send(JSON.stringify(data));
    }
  }

  function reconnect(
    url: string,
    connectionKey: string,
    activeToken: string,
    callBack: (data: any) => void
  ) {
    // 清除可能存在的活跃定时器
    if (activeTimer) {
      clearInterval(activeTimer);
    }

    reconnectIng = true;

    // 如果 WebSocket 已存在且处于 OPEN 状态，无需重新连接
    if (
      webSocket &&
      webSocket.readyState === WebSocket.OPEN &&
      !activeClose
    ) {
      return;
    }

    // 满足重连条件时，尝试重新连接
    if (
      reconnectIng &&
      reconnectCount < 10 &&
      reconnectTime + 10000 < Date.now() &&
      !activeClose
    ) {
      reconnectCount++;
      reconnectTime = Date.now();
      reconnectTimer = setInterval(() => {
        const ws = InitWS(url, connectionKey, activeToken, callBack);
        // 若重连成功，则停止重连计时器
        if (ws && ws.readyState === WebSocket.OPEN) {
          if (reconnectTimer) {
            clearInterval(reconnectTimer);
          }
        }
      }, 2000);
    }
  }

  function destroy() {
    try {
      // 清除活跃定时器
      if (activeTimer) {
        clearInterval(activeTimer);
      }
      // 设置主动关闭标志并关闭WebSocket连接
      activeClose = true;
      if (webSocket) {
        webSocket.close();
      }
    } catch (error) {
      // 捕获并记录可能发生的异常
      console.error("destroy ws error:", error);
    }
  }

  return {
    webSocket,
    InitWS,
    destroy,
    send,
  };
}, { persist: true });
